@extends('layouts.base')

@section('title', '兑换记录')

@push('styles')
<style>
    @keyframes float {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-20px) rotate(180deg); }
    }
    
    @keyframes bounce {
        0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
        40% { transform: translateY(-10px); }
        60% { transform: translateY(-5px); }
    }
    
    .history-container {
        padding: 20px;
    }
    
    .filter-tabs {
        background: white;
        border-radius: 16px;
        padding: 8px;
        margin-bottom: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        display: flex;
    }
    
    .filter-tab {
        flex: 1;
        background: transparent;
        border: none;
        padding: 12px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 600;
        color: #718096;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .filter-tab.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .records-list {
        margin-bottom: 20px;
    }
    
    .record-item {
        background: white;
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 15px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .record-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 30px rgba(0,0,0,0.12);
    }
    
    .record-item::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
    }
    
    .record-item.success::before {
        background: #48bb78;
    }
    
    .record-item.failed::before {
        background: #f56565;
    }
    
    .record-item.expired::before {
        background: #ed8936;
    }
    
    .record-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 15px;
    }
    
    .record-info {
        flex: 1;
    }
    
    .record-code {
        font-size: 16px;
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 5px;
        font-family: 'Courier New', monospace;
        letter-spacing: 1px;
    }
    
    .record-type {
        font-size: 14px;
        color: #667eea;
        font-weight: 600;
    }
    
    .record-status {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-align: center;
        min-width: 60px;
    }
    
    .status-success {
        background: #c6f6d5;
        color: #2f855a;
    }
    
    .status-failed {
        background: #fed7d7;
        color: #c53030;
    }
    
    .status-expired {
        background: #feebc8;
        color: #c05621;
    }
    
    .record-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
        font-size: 14px;
    }
    
    .record-details.three-columns {
        grid-template-columns: 1fr 1fr 1fr;
    }
    
    .detail-item {
        display: flex;
        flex-direction: column;
    }
    
    .detail-label {
        color: #718096;
        margin-bottom: 4px;
        font-size: 12px;
    }
    
    .detail-value {
        color: #2d3748;
        font-weight: 600;
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #718096;
    }
    
    .empty-icon {
        font-size: 64px;
        margin-bottom: 20px;
        opacity: 0.5;
    }
    
    .empty-title {
        font-size: 18px;
        font-weight: 600;
        margin: auto 0;
        color: #4a5568;
    }
    
    .empty-desc {
        font-size: 14px;
        line-height: 1.5;
    }
    
    .stats-card {
        background: white;
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    }
    
    .stats-title {
        font-size: 16px;
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 15px;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
    }
    
    .stat-item {
        text-align: center;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 12px;
    }
    
    .stat-number {
        font-size: 24px;
        font-weight: 700;
        color: #667eea;
        margin-bottom: 5px;
    }
    
    .stat-label {
        font-size: 12px;
        color: #718096;
    }
    
    .loading-spinner {
        text-align: center;
        padding: 20px;
        display: none;
    }
    
    .loading-spinner .spinner {
        width: 40px;
        height: 40px;
        margin: 0 auto;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>
@endpush

@section('content')
<div class="page-header">
    <button class="back-btn" onclick="window.location.href = '{{ route('membership.redeem') }}'"><</button>
    <div class="page-icon">📋</div>
    <div class="page-title">兑换记录</div>
    <div class="page-subtitle">查看所有兑换历史</div>
</div>

<div class="history-container">
    <!-- <div class="stats-card" id="statsCard">
        <div class="stats-title">兑换统计</div>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-number" id="totalCount">0</div>
                <div class="stat-label">总兑换</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="successCount">0</div>
                <div class="stat-label">成功</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="failedCount">0</div>
                <div class="stat-label">失败</div>
            </div>
        </div>
    </div>
    
    <div class="filter-tabs">
        <button class="filter-tab active" data-filter="all">全部</button>
        <button class="filter-tab" data-filter="success">成功</button>
        <button class="filter-tab" data-filter="failed">失败</button>
    </div> -->
    
    <div class="records-list" id="recordsList">
        <!-- 记录将通过JavaScript动态加载 -->
    </div>
    
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner"></div>
    </div>
    
    <div class="empty-state" id="emptyState" style="display: none;">
        <div class="empty-icon">📝</div>
        <div class="empty-title">暂无兑换记录</div>
        <!-- <div class="empty-desc">您还没有进行过任何兑换操作<br>快去获取兑换码体验会员特权吧</div> -->
    </div>
</div>
@endsection

@push('scripts')
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
<script>
    let currentFilter = 'all';
    let currentPage = 1;
    let lastPage = 1;
    let isLoading = false;
    let records = [];
    
    // 页面加载时初始化
    $(document).ready(function() {
        loadRecords(true);
        
        // 筛选标签点击事件
        $('.filter-tab').click(function() {
            $('.filter-tab').removeClass('active');
            $(this).addClass('active');
            currentFilter = $(this).data('filter');
            currentPage = 1;
            records = [];
            loadRecords(true);
        });
        
        // 滚动加载更多
        $(window).scroll(function() {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
                if (!isLoading && currentPage < lastPage) {
                    loadMoreRecords();
                }
            }
        });
    });
    
    // 加载兑换记录
    function loadRecords(reset = false) {
        if (isLoading) return;
        
        isLoading = true;
        
        if (reset) {
            $('#recordsList').empty();
            $('#loadingSpinner').show();
        }
        
        $.ajax({
            url: '{{ route("membership.history.data") }}',
            type: 'GET',
            data: {
                filter: currentFilter,
                page: currentPage,
                per_page: 10
            },
            success: function(response) {
                isLoading = false;
                $('#loadingSpinner').hide();
                
                if (reset) {
                    records = response.data;
                } else {
                    records = records.concat(response.data);
                }
                
                // 更新分页信息
                currentPage = response.meta.current_page;
                lastPage = response.meta.last_page;
                
                // 更新统计信息
                updateStats(response.stats);
                
                // 渲染记录
                renderRecords(response.data, reset);
                
                // 显示空状态
                if (records.length === 0) {
                    $('#emptyState').show();
                } else {
                    $('#emptyState').hide();
                }
            },
            error: function(error) {
                isLoading = false;
                $('#loadingSpinner').hide();
                console.error('加载记录失败:', error);
            }
        });
    }
    
    // 加载更多记录
    function loadMoreRecords() {
        if (currentPage >= lastPage) return;
        
        currentPage++;
        loadRecords(false);
    }
    
    // 渲染记录列表
    function renderRecords(records, reset = false) {
        const container = $('#recordsList');
        
        if (reset) {
            container.empty();
        }
        
        if (records.length === 0 && container.children().length === 0) {
            return;
        }
        
        const html = records.map(record => {
            const statusClass = getStatusClass(record.status);
            const statusText = getStatusText(record.status);
            
            // 判断是否为日卡并获取天数信息
            const isDayCard = record.memberType && record.memberType.includes('日卡');
            const dayCount = isDayCard ? extractDayCount(record.memberType) : null;
            const memberTypeDisplay = isDayCard && dayCount ? `${dayCount}天日卡` : (record.memberType || '兑换失败');
            
            return `
                <div class="record-item ${record.status}">
                    <div class="record-header">
                        <div class="record-info">
                            <div class="record-code">${record.code}</div>
                            <div class="record-type">${memberTypeDisplay}</div>
                        </div>
                        <div class="record-status ${statusClass}">${statusText}</div>
                    </div>
                    <div class="record-details ${record.status === 'success' ? 'three-columns' : ''}">
                        <div class="detail-item">
                            <div class="detail-label">兑换日期</div>
                            <div class="detail-value">${formatDate(record.redeemDate)}</div>
                        </div>
                        ${record.status === 'success' ? `
                            <div class="detail-item">
                                <div class="detail-label">生效开始</div>
                                <div class="detail-value">${formatDate(record.startDate)}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">生效结束</div>
                                <div class="detail-value">${formatDate(record.endDate)}</div>
                            </div>
                        ` : `
                            <div class="detail-item">
                                <div class="detail-label">失败原因</div>
                                <div class="detail-value">${getFailureReason(record.status)}</div>
                            </div>
                        `}
                    </div>
                </div>
            `;
        }).join('');
        
        if (reset) {
            container.html(html);
        } else {
            container.append(html);
        }
        
        // 添加动画效果
        $('.record-item').each(function(index) {
            const $this = $(this);
            if (!$this.hasClass('animated')) {
                $this.addClass('animated');
                $this.css({
                    'opacity': '0',
                    'transform': 'translateY(20px)'
                }).delay(index * 50).animate({
                    'opacity': '1'
                }, 300).css('transform', 'translateY(0)');
            }
        });
    }
    
    // 更新统计信息
    function updateStats(stats) {
        $('#totalCount').text(stats.total);
        $('#successCount').text(stats.success);
        $('#failedCount').text(stats.failed);
    }
    
    // 获取状态样式类
    function getStatusClass(status) {
        switch (status) {
            case 'success': return 'status-success';
            case 'failed': return 'status-failed';
            case 'expired': return 'status-expired';
            default: return 'status-failed';
        }
    }
    
    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 'success': return '成功';
            case 'failed': return '失败';
            case 'expired': return '已过期';
            default: return '失败';
        }
    }
    
    // 获取失败原因
    function getFailureReason(status) {
        switch (status) {
            case 'failed': return '兑换码无效';
            case 'expired': return '会员已过期';
            default: return '未知错误';
        }
    }
    
    // 提取日卡天数
    function extractDayCount(memberType) {
        if (!memberType) return null;
        const match = memberType.match(/(\d+)天?日卡?/);
        return match ? match[1] : null;
    }
    
    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
</script>
@endpush